<?php
// +----------------------------------------------------------------------
// | Author: yaoyihong <510974211@qq.com>
// +----------------------------------------------------------------------

namespace app\api\logic;

use \tpfcore\Core;
use think\Validate;
use think\Request;
use think\Db;
use \tpfcore\helpers\StringHelper;
class User extends ApiBase
{
    public $ids=[];
    public function wx_login($data = [])
    {
        $request = Request::instance();
        
        // 如果token为空或在数据库不存在，表示未登录
        if(!empty($request->header("Auth-Token")) && Core::loadModel($this->name)->getStatistics(["token"=>$request->header("Auth-Token")])>0){
            return [0, 'success'];
        }else{

            $info = Db::name('WechatConfig')->order('id desc')->value('value');
            $info = json_decode($info,true);

            if(empty($info) || empty($info['wechat_appid']) || empty($info['wechat_appsecret'])){
                return [-4,"请先配置好微信公众号"];
            }

            $appid     = $info['wechat_appid'];

            return [-1,"未登录",$appid];
        }
    }

    /* 获取token */
    public function getToken($data=[])
    {
        $result = Core::loadAddonModel("Wechat","wechat_config","controller")->getUserInfo($data);
/*$result = '';*/
        if(empty($result[2]['errcode'])){
            $userinfo = $result[2];
/*$userinfo = [
    'openid'=>'aaaaaaaaaaaaaa',
    'nickname' => '阳先生',
    'headimgurl' => '/dkgjkdgkdgjdkg'
];*/
// dump($userinfo);die;

            // 如果有就生成token返回，没有就写入返回token
            $openid = $userinfo['openid'];

            $token = StringHelper::get_random_string(32);
            $data['token']=md5($token.time());

            $result = self::getOneObject(['openid'=>$openid], 'id,isresult');

            if(!empty($result)){
                $data['id']=$result['id'];
            }else{
                $data['openid']=$openid;
                $data['nickname']=$userinfo['nickname'];
                $data['headimg']=$userinfo['headimgurl'];
                $data['create_time'] = time();
            }

            $res = self::saveObject($data, ['openid','nickname','headimg','token','create_time']);
            if (!$res) {
                return [-1, "登录失败"];
            }

            if ($result && $result->isresult === 0) {
                return [-2, "需要完善信息", $data['token']];
            }

            return [0, "success", $data['token']];
        }else{
            return [-1, $result[2]['errmsg']];
        }
    }

    public function getUserInfo($data)
    {
        $request = Request::instance();

        $result = Core::loadModel($this->name)->getList([
           "where" =>["__USER__.token"=>$request->header("Auth-Token")],
           "field"=>"__USER__.id,__USER__.headimg,__USER__.nickname,__USER__.money,__USER__.integral,__USER__.profit,__USER__.gender,__USER__.level,__USER__.isresult,__USER_STATISTICS__.total_integral",
           "join"=>["join"=>"__USER_STATISTICS__","condition"=>"__USER__.id=__USER_STATISTICS__.user_id","type"=>"left"]
        ]);
        if(empty($result)){
            return [-1,"请重新登录"];
        }

        $result['recommender_number'] = count($this->getChildIds($result[0]['id']));
        
        return [0,"success",$result[0]];
    }

    private function getChildIds($parent_id=0){
        $result = self::getList(["where"=>['parent_id'=>$parent_id]]);
        foreach ($result as $key => $value) {
            $this->ids[]=$value['id'];
            $this->getChildIds($value['id']);
        }
        return $this->ids;
    }


    public function updateUserInfo($data=[])
    {
        $validate = \think\Loader::validate($this->name);
        $validate_result = $validate->scene('updateUserInfo')->check($data);
        if (!$validate_result) {
            return [4003, $validate->getError()];
        }

        $request = Request::instance();
        $result = self::updateObject(["token"=>$request->header("Auth-Token")], $data, ['nickname','headimg']);
        if($result){
            return [0,"修改成功"];
        }else{
            return [-1,"修改失败"];
        }
    }
    public function getRecommender($data=[]){
        $request = Request::instance();
        $userid = Core::loadModel($this->name)->getColumnValue(["token"=>$request->header("Auth-Token")],"id");
        $result = Core::loadModel($this->name)->getList([
            "field"=>["password","privs","role_id"],
            "where"=>['parent_id'=>$userid],
            "order"=>"create_time desc",
            "paginate"  =>['rows' => DB_LIST_ROWS],
        ]);
        return [0,"success",$result];
    }
    public function getUserStatistics(){
        $userinfo=$this->getBaseUserInfo();
        $userid=$userinfo['id'];
        $result = Core::loadModel($this->name)->getList([
            "where"=>["__USER__.id"=>$userid],
            "field"=>"__USER__.money,__USER__.integral,__USER__.profit,__USER__.headimg,__USER__.nickname,__USER_STATISTICS__.total_money,__USER_STATISTICS__.total_profit,__USER_STATISTICS__.total_cashout",
            "join"=>["join"=>"__USER_STATISTICS__","condition"=>"__USER__.id=__USER_STATISTICS__.user_id","type"=>"left"]
        ]);
        return [0,"success",$result];
    }
    public function checkPayPassword($data=[]){
        return [0,"success"];
        $userinfo=$this->getBaseUserInfo();
        $userid=$userinfo['id'];
        if(self::getStatistics(["id"=>$userid,"pay_password"=>$data['password']])>0){
            // 确认收货
            if(isset($data['type']) && $data['type']=="confirm_order"){
                $result = Core::loadAddonModel("Order","mall","logic")->updateOrder(["order_sn"=>$data['order_sn'],"user_id"=>$$userid],["order_status"=>3,"shipping_status"=>3,"pay_status"=>1]);
                if($result){
                    return [0,"success"];
                }
                return [400049,"确认失败"];
            }
            return [0,"success"];
        }
        return [400048,"支付密码错误"];
    }
}